package com.community.backend.controller;

import com.community.backend.context.BaseContext;
import com.community.backend.pojo.Admin;
import com.community.backend.pojo.Property;
import com.community.backend.pojo.Security;
import com.community.backend.pojo.User;
import com.community.backend.pojo.dto.LoginDTO;
import com.community.backend.pojo.dto.RegisterDTO;
import com.community.backend.pojo.vo.LoginVO;
import com.community.backend.properties.JwtProperties;
import com.community.backend.service.AdminService;
import com.community.backend.service.PropertyService;
import com.community.backend.service.SecurityService;
import com.community.backend.service.UserService;
import com.community.backend.utils.JwtUtil;
import com.community.backend.utils.RedisUtils;
import com.community.backend.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/loginAndRegister")
public class LoginAndRegisterController {
    private final UserService userService;
    private final PropertyService propertyService;
    private final SecurityService securityService;
    private final AdminService adminService;
    private final JwtProperties jwtProperties;


    public LoginAndRegisterController(UserService userService, PropertyService propertyService, SecurityService securityService, AdminService adminService, JwtProperties jwtProperties) {
        this.userService = userService;
        this.propertyService = propertyService;
        this.securityService = securityService;
        this.adminService = adminService;
        this.jwtProperties = jwtProperties;
    }

/**
 * 只有用户需要注册
 * 注册
 */
    @PostMapping("/register")
    public Result register(@RequestBody RegisterDTO registerDTO){
        log.info("用户注册：{}", registerDTO);
        registerDTO.setStatus("已注册");
        userService.register(registerDTO);
        return Result.success();
    }

    /**
     * 退出登录
     * 如果用户只点进首页就退出，那么Redis中存储的token就会过期，但是用户信息不会被删除
     * @return
     */
    @PostMapping("/loginOut")
    public Result loginOut(){
        log.info("用户退出登录");
        String id = BaseContext.getCurrentId();
        String role = BaseContext.getCurrentRole();
        if (id == null || role == null) {
            log.warn("用户退出登录失败：上下文信息不完整，id={}, role={}", id, role);
            return Result.error("会话已过期");
        }
        String key = "login:" + role + ":" + id;
        System.out.println("用户退出登录key"+key);
        System.out.println("用户退出登录"+RedisUtils.redis().getExpire( key));
        Boolean delete = RedisUtils.redis().delete(key);
//        BaseContext.removeCurrentId();
//        BaseContext.removeCurrentName();
//        BaseContext.removeCurrentRole();
        System.out.println("用户退出登录"+delete);
        System.out.println("用户退出登录"+BaseContext.getCurrentName());
        return Result.success("退出登录");
    }
    @PostMapping("/login")
    public Result login(@RequestBody LoginDTO loginDTO){
        String role = loginDTO.getRole();
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("role", role);
        LoginVO loginVO = new LoginVO();
        String id = null;
        Object userInfo = null; // 用于存储用户信息
        if (role == null) {
            return Result.error("角色信息不能为空");
        }
        if (role.equals("USER")){
            User user = userService.login(loginDTO);
            System.out.println("登录用户" + user);
            if (user != null && user.getStatus().equals("启用")) {
                claims.put("userId", user.getId());
                claims.put("name", user.getName());
                userInfo = user; // 保存用户信息
                id = String.valueOf(user.getId());
                loginVO.setRole("USER");
                System.out.println("qqq登录用户" + user);
            } else {
                System.out.println("error登录用户" + user);
                return Result.error("用户名或密码错误");
            }
        } else if (role.equals("PROPERTY")){
            Property property = propertyService.login(loginDTO);
            if (property != null) {
                claims.put("propertyId", property.getId());
                claims.put("name", property.getName());
                userInfo = property; // 保存物业信息
                id = String.valueOf(property.getId());
                loginVO.setRole("PROPERTY");
            } else {
                return Result.error("用户名或密码错误");
            }
        } else if (role.equals("SECURITY")) {
            Security security = securityService.login(loginDTO);
            if (security != null){
                claims.put("securityId", security.getId());
                claims.put("name", security.getName());

                System.out.println("登录用户" + security);
                userInfo = security;
                id = String.valueOf(security.getId());
                loginVO.setRole("SECURITY");
            }else {
                return Result.error("用户名或密码错误");
            }
        } else if (role.equals("ADMIN")){
            Admin admin = adminService.login(loginDTO);
            if (admin != null) {
                claims.put("adminId", admin.getId());
                claims.put("name", admin.getName());
                userInfo = admin; // 保存管理员信息
                id = String.valueOf(admin.getId());
                loginVO.setRole("ADMIN");
            } else {
                return Result.error("用户名或密码错误");
            }
        } else {
            return Result.error("不支持的角色类型");
        }
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        loginVO.setToken(token);
        // 假设LoginVO添加了userInfo字段用于返回用户信息
         loginVO.setUserInfo(userInfo);
         // 将token保存到Redis中
        String key = "login:" + role + ":" + id;
        RedisUtils.redis().opsForValue().set(key, loginVO.getToken(), jwtProperties.getUserTtl(), TimeUnit.MILLISECONDS);//毫秒 2小时过期
        System.out.println("登录用户" + loginVO);

        return Result.success(loginVO);
    }


}
